# _*_coding:utf-8_*_
"""
    ATS read hardware config file module.
    Created by Ivy.Li 2013.06.03.
    (C)Copyright 2013 Hech. All rights reserved
"""
import configparser as ConfigParser
import os
import pathlib
from ATS.util import constant

# from ATS.proberdriver import Prober

inst_dict = {}

'''
 读取配置文件中的设备list
 
'''


def getinstconfig(file_name=None):
    if file_name is None:
        file_name = constant.RCF_PATH / pathlib.Path("online.rcf")
        # file_name = os.path.join(constant.RCF_PATH, "online.rcf")
    config = ConfigParser.ConfigParser()
    config.read(file_name)
    inst_list = config.get("INSTRUMENTATION", "LIST")
    if not inst_list.strip():
        inst_list = []
    else:
        inst_list = inst_list.split(",")
    b1500inst_list = []
    for inst in inst_list:
        inst = inst.strip()
        info_dict = {}
        items = config.items(inst)

        for i in items:
            if i[1].isdigit() and len(i[1]) <= 5:
                info_dict[i[0]] = eval(i[1])
            else:
                info_dict[i[0]] = i[1]
        if "class" in info_dict:
            m = __import__("instrumentDriver.InstGen%s.InstGen%s" % (info_dict["type"], info_dict["class"]))
            c_name = "m.InstGen%s.InstGen%s.%s" % (info_dict["type"], info_dict["class"], info_dict["class"])
            inst_dict[inst] = eval(c_name)(inst)
            # inst_dict[inst] = eval(c_name)(inst, info_dict)
        elif 'prober_addr' in info_dict:  # TBD
            pass
            # Prober.set_prb_info(info_dict)
        if info_dict.get("model") == "B1500A":
            if info_dict.get("is_master") == 1:
                b1500inst_list.insert(0, inst)
            else:
                b1500inst_list.append(inst)
    # update B1500 instrument control handler
    if len(b1500inst_list) > 1:
        handler = inst_dict[b1500inst_list[0]].getinsthandler()
        for i in b1500inst_list[1:]:
            inst_dict[i].setinsthandler(handler)


# 获得inst_dict
def get_inst_dict():
    global inst_dict
    return inst_dict


def get_info_dict(section):
    # file_name = os.path.join(constant.RCF_PATH, "online.rcf")
    file_name = constant.RCF_PATH / pathlib.Path("online.rcf")
    # print(file_name)
    config = ConfigParser.ConfigParser()
    config.read(file_name)
    items = config.items(section)
    return dict(items)
